package net.begincode.servlet.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.BQStringUtil;
import net.begincode.bean.BcUser;
import net.begincode.service.blog.BlogService;
import net.begincode.service.blog.ClassifyService;
import net.begincode.service.blog.impl.BlogServiceImpl;
import net.begincode.service.blog.impl.ClassifyServiceImpl;
import net.begincode.service.chapter.impl.ChapterServiceImpl;
import net.begincode.service.code.impl.CodeServiceImpl;
import net.begincode.service.course.impl.CourseServiceImpl;
import net.begincode.service.down.impl.BcDownServiceImpl;
import net.begincode.service.manager.impl.ManagerServiceImpl;
import net.begincode.service.project.impl.ProjectServiceImpl;
import net.begincode.service.project.impl.ProjectStageServiceImpl;
import net.begincode.service.user.BcUserService;
import net.begincode.service.user.impl.BcUserServiceImpl;


public class BaseServlet {
	public static final int PAGE_COUNT = 10;//每页显示数据条数
	public static final String INIT_POWER="110"; //权限字符串
	
	//一级目录
	public static final int TOP_NAV = 0; //顶级目录
	public static final int BASEC_OURSE = 1;//基础教程
	public static final int CODE_SHARE = 3;//代码分享
	public static final int DATABASE = 5;//数据库
	public static final int PROJECT = 8;//项目
	public static final int DOWNLOAD = 11;// 下载管理
	//课程标识
	public static final int JAVA_SOURSE = 1;
	public static final int DATA_BASE = 3;
	public static final int MYSQLDATABASE = 2;
	//下载标识
	public static final int TOOL = 12 ;
	public static final int BOOK = 13;
	public static final int FRAME = 14;
	
 	public BcUserService bcUserService;
 	public ClassifyService classifyService;
 	public BlogService blogService;
 	public CourseServiceImpl courseService;
 	public ManagerServiceImpl managerService;
 	public CodeServiceImpl codeService;
 	public ChapterServiceImpl chapterService;
 	public ProjectServiceImpl projectService;
 	public ProjectStageServiceImpl projectStageService;
 	public BcDownServiceImpl bcDownService;
	public BaseServlet() {
		// TODO Auto-generated constructor stub
		bcUserService = BcUserServiceImpl.getInstance();
		classifyService = ClassifyServiceImpl.getInstance();
		blogService = BlogServiceImpl.getInstance();
		courseService = CourseServiceImpl.getInstance();
		managerService = ManagerServiceImpl.getInstance();
		codeService = CodeServiceImpl.getInstance();
		chapterService = ChapterServiceImpl.getInstance();
		projectService = ProjectServiceImpl.getInstance();
		projectStageService = ProjectStageServiceImpl.getInstance();
		bcDownService = BcDownServiceImpl.getInstance();
	}
	//获取客户端IP
	public String getRemoteHost(HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}
	//获取客户端浏览器信息
	public String getRemoteBroswer(HttpServletRequest request){
		try{
			String agent = request.getHeader("user-agent");
			return agent ;
		}catch(Exception e){
			return "";
		}
	}
	/**
	 * 获取日期字符串
	 * */
	public String getDataCode(){
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return sd.format(new Date());
	}
	/**
	 * 用户信息，保存到cookie中
	 * */
	public void addUserCookie(BcUser bcUser,String flag,HttpServletResponse response) throws UnsupportedEncodingException{
		// 将登录信息保存到cookie中
		Cookie nickNameCookie = new Cookie("nickName", URLEncoder.encode(bcUser.getNickname(), "utf-8"));
//		Cookie emailCookie = new Cookie("email",bcUser.getEmail());
		Cookie bcUserIdCookie = new Cookie("bcUserId",String.valueOf(bcUser.getBc_user_id()));
		Cookie beginidCookie = new Cookie("beginid",bcUser.getBeginid());
		//设置关闭浏览器过期
		if(flag != null && flag.equals("1")){
			//设置过期时间一年
			nickNameCookie.setMaxAge(365*24*60*60);
//			emailCookie.setMaxAge(365*24*60*60);
			bcUserIdCookie.setMaxAge(365*24*60*60);
			beginidCookie.setMaxAge(365*24*60*60);
		}else{
			//设置关闭浏览器过期
			nickNameCookie.setMaxAge(-1);
//			emailCookie.setMaxAge(-1);
			bcUserIdCookie.setMaxAge(-1);
			beginidCookie.setMaxAge(-1);
		}
		nickNameCookie.setPath("/");
//		emailCookie.setPath("/");
		bcUserIdCookie.setPath("/");
		beginidCookie.setPath("/");
		// 设置路径，这个路径即该工程下都可以访问该cookie
		// 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
		response.addCookie(nickNameCookie);
//		response.addCookie(emailCookie);
		response.addCookie(bcUserIdCookie);
		response.addCookie(beginidCookie);
	}
	/**
	 * 获取cookie信息，并存储map返回
	 * */
	public Map<String,String> getCookieInfo(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		Map cookieMap = new HashMap();
		Cookie[] cookies = request.getCookies();//获取cookie
		if(cookies != null){
		for(Cookie cookie : cookies){
			if(cookie.getName().equals("nickName")){
				cookieMap.put("nickName", URLDecoder.decode(cookie.getValue(),"utf-8"));
			}
//			if(cookie.getName().equals("email")){
//				cookieMap.put("email", cookie.getValue());
//			}
			if(cookie.getName().equals("bcUserId")){
				cookieMap.put("bcUserId", cookie.getValue());
			}
			if(cookie.getName().equals("beginid")){
				cookieMap.put("beginid", cookie.getValue());
			}
		}
		}
		return cookieMap;
	}
	
	/**
	 * 注销，清除cookie信息
	 * */
	public void delCookieInfo(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		// 将登录信息保存到cookie中
		Cookie nickNameCookie = new Cookie("nickName", null);
//		Cookie emailCookie = new Cookie("email",null);
		Cookie bcUserIdCookie = new Cookie("bcUserId",null);
		Cookie beginidCookie = new Cookie("beginid",null);
		nickNameCookie.setMaxAge(0);
//		emailCookie.setMaxAge(0);
		bcUserIdCookie.setMaxAge(0);
		beginidCookie.setMaxAge(0);
		nickNameCookie.setPath("/");
//		emailCookie.setPath("/");
		bcUserIdCookie.setPath("/");
		beginidCookie.setPath("/");
		// 设置路径，这个路径即该工程下都可以访问该cookie
		// 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
		response.addCookie(nickNameCookie);
//		response.addCookie(emailCookie);
		response.addCookie(bcUserIdCookie);
		response.addCookie(beginidCookie);
	}
	/**
	 * 验证cookie中信息是否正确，用户名密码
	 * @throws UnsupportedEncodingException 
	 * */
	public boolean checkUser(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		Map useMap = this.getCookieInfo(request, response);
		if(useMap != null){
			if(useMap.get("beginid") != null){
				BcUser bcUser = bcUserService.selUserByBeginId(useMap.get("beginid").toString());
				if(bcUser != null){
					return true;
				}
			}
		}else{
			return false;
		}
		
		return false;
	}
	//查询基础教程下目录
	public void selBaseCourseNav(HttpServletRequest request){
		request.setAttribute("bcnavs", this.managerService.selNavByPid(this.BASEC_OURSE));
	}
	//查询代码分享下目录
	public void selCodeShareNav(HttpServletRequest request){
		request.setAttribute("codenavs", this.managerService.selNavByPid(this.CODE_SHARE));
	}
	//查询下载管理下目录
	public void selDownNav(HttpServletRequest request){
		request.setAttribute("downnavs", this.managerService.selNavByPid(this.DOWNLOAD));
	}	
}
